package com.giw.uima.annotator;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.uima.TokenAnnotation;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.util.Level;

import com.giw.uima.ts.PersonAnnotation;

public class PersonAnnotator extends JCasAnnotator_ImplBase{

	private static final String SURNAMEDICTS_PATH = "dictionary_surname";

	private List<String> personList;

	
	public void initialize(UimaContext aContext) throws ResourceInitializationException {
		super.initialize(aContext);
		try {
			this.personList = IOUtils.readLines(new FileInputStream(String.valueOf(aContext
					.getConfigParameterValue(SURNAMEDICTS_PATH))));
			Collections.sort(personList); // sort collection to make binary search possible
		} catch (IOException e) {
			e.printStackTrace();
			aContext.getLogger().log(Level.SEVERE, "error reading dictionary_surname file");
			throw new ResourceInitializationException(e);
		}
	}

	public void process(JCas jcas) throws AnalysisEngineProcessException {
	    for (Annotation annotation : jcas.getAnnotationIndex(TokenAnnotation.type)) {
	      //System.out.println(annotation.getCoveredText());
	      if (Collections.binarySearch(personList, annotation.getCoveredText()) >= 0 && isUP(annotation)) {
	    	//System.out.println(annotation.getCoveredText());
	        PersonAnnotation personAnnotation = new PersonAnnotation(jcas);
	        personAnnotation.setBegin(annotation.getBegin());
	        personAnnotation.setEnd(annotation.getEnd());
	        personAnnotation.addToIndexes();
	      }
	    }
	  }
	
	private boolean isUP(Annotation annotation) {
		String text=annotation.getCoveredText();
		Character c=text.charAt(0);
		return Character.isUpperCase(c);
	}

}
